<template>
  <CodeMirror v-if="type === 'default'" :tab="tab" />
  <ImageEditor v-else-if="type === 'imageEditor'" :path="path" />
  <UnknownEditor v-else-if="type === 'editorWithPreview'" :path="path" :size="size" />
  <UnknownEditor v-else :path="path" :size="size" />
</template>

<script>
  import CodeMirror from '../editor-code-mirror'
  import ImageEditor from '../editor-image'
  import UnknownEditor from '../editor-unknown'
  import { FileTypes } from 'utils'

  const typeDetect = (title, types) => {
    // title is the filename
    // typeArray is the suffix
    if (!Array.isArray(types)) return title.endsWith(`.${types}`)
    return types.reduce((p, v) => p || title.endsWith(`.${v}`), false)
  }

  export default {
    components: { CodeMirror, ImageEditor, UnknownEditor },
    props: { tab: { default: {}, type: Object } },
    computed: {
      type: function () {
        let type = 'default'
        if (this.tab.contentType) {
          const contentType = FileTypes.getFileType(this.tab.contentType)
          if (contentType === 'IMAGE') {
            type = 'imageEditor'
          } else if (contentType === 'UNKNOWN') {
            type = 'unknownEditor'
          }
        }
        const title = this.tab.title
        if (typeDetect(title, 'md')) {
          type = 'editorWithPreview'
        }
        if (typeDetect(title, ['png', 'jpg', 'jpeg', 'gif'])) {
          type = 'imageEditor'
        }
        return type
      },
      body: function () {
        return this.tab.content ? this.tab.content : {}
      },
      path: function () {
        return this.tab.path ? this.tab.path : ''
      },
      size: function () {
        return this.tab.size ? this.tab.size : 0
      }
    }
  }

</script>
